package com.zz.websockettest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    private WebSocketServer webSocketServer;
    private TextView ipInfo;
    private TextView info;
    private String ip;
    private Handler handler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ipInfo = findViewById(R.id.ip_info);
        info = findViewById(R.id.info);
        webSocketServer = new WebSocketServer(new InetSocketAddress(6666)) {
            @Override
            public void onStart() {
                handler.post(() -> {
                    info.append(getLocalTime() + "onStart");
                    Toast.makeText(MainActivity.this, "onstart", Toast.LENGTH_LONG).show();
                    Log.i("eeeeee", "onStart");
                });
            }

            @Override
            public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
                handler.post(() -> {

                    info.append(getLocalTime() + "onOpen localip = " + webSocket.getLocalSocketAddress()
                    + "  remoteip = " + webSocket.getRemoteSocketAddress());
                    Toast.makeText(MainActivity.this, "onOpen", Toast.LENGTH_LONG).show();
                    Log.i("eeeeee", "onOpen： " + webSocket);
                });
            }

            @Override
            public void onClose(WebSocket webSocket, int code, String reason, boolean remote) {
                handler.post(() -> {
                    String s = "onClose: localip = " + webSocket.getLocalSocketAddress() +
                            "  remoteip = " + webSocket.getRemoteSocketAddress() +
                            " code = " + code + " reason = " + reason + " remote = " + remote;
                    info.append(getLocalTime() + s);
                    Toast.makeText(MainActivity.this, "onClose: webSocket code = " + code + " reason = " + reason + " remote = " + remote, Toast.LENGTH_LONG).show();
                    Log.i("eeeeee", "onClose: webSocket code = " + code + " reason = " + reason + " remote = " + remote);
                });
            }

            @Override
            public void onMessage(WebSocket webSocket, String message) {
                handler.post(() -> {
                    info.append(getLocalTime() + "onMessage = " + message);
                    webSocket.send(message + "+++");
                    Toast.makeText(MainActivity.this, "onMessage = " + message, Toast.LENGTH_LONG).show();
                    Log.i("eeeeee", "onMessage = " + message);
                });
            }

            @Override
            public void onMessage(WebSocket conn, ByteBuffer bytes) {

            }

            @Override
            public void onError(WebSocket webSocket, Exception e) {
                handler.post(() -> {
                    String s = "onError: localip = " + webSocket.getLocalSocketAddress() +
                            "  remoteip = " + webSocket.getRemoteSocketAddress();
                    info.append(getLocalTime() + s);
                    Toast.makeText(MainActivity.this, "e = " + e.getMessage(), Toast.LENGTH_LONG).show();
                    Log.i("eeeeee", "e = " + e.getMessage());
                });
            }
        };
        webSocketServer.setReuseAddr(true);
        webSocketServer.setConnectionLostTimeout(10);
        webSocketServer.start();


    }

    private String getLocalTime() {
        URL url = null;//取得资源对象
        try {
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            String format = formatter.format(calendar.getTime());
            String s = "\n" + format.split(" ")[1] + "   ";
            return s;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setIpMessage();
    }

    private void setIpMessage() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.isWifiEnabled()) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            ip = getIpString(wifiInfo.getIpAddress());
            ipInfo.append("\n" + ip + ":6666");
        }
    }

    //将获取到的int型ip转成string类型
    private String getIpString(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "."
                + ((i >> 16) & 0xFF) + "." + (i >> 24 & 0xFF);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            webSocketServer.stop();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}